package io.github.biezhi.elves.utils;

import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;

import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.ok.http.FastHttpClient;
import io.github.biezhi.elves.utils.FileUtil;
import io.github.biezhi.elves.utils.HttpUtil;

/**
 * 百度云api工具类
 * 
 *
 */
public class BaiduApiUtils {
	static final String proxyIp = "132.122.1.4";
	static final int proxyPort = 9898;
	
	static final String APPID = "11165779";
	static final String APIKEY = "fdpUjEyZKi4lueH8rY4CsPG0";
	static final String SECRETKEY = "LFKEFdcPlmwBrbf2z2CPOCYvaLicOTF3";
	
	static String accessToken = "";
	
	static final String baiduUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general";
	static final String accessTokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=fdpUjEyZKi4lueH8rY4CsPG0&client_secret=LFKEFdcPlmwBrbf2z2CPOCYvaLicOTF3&";
	
	/**
	 * 通用文字识别（含位置高精度版）
	 * 
	 * 接口描述:用户向服务请求识别某张图中的所有文字，并返回文字在图片中的坐标信息，
	 * 相对于通用文字识别（含位置信息版）该产品精度更高，但是识别耗时会稍长。。
	 * 
	 * @param imgData
	 * @return
	 * @throws Exception 
	 */
	public static String getBaiduApiForAccurate(String imgData) throws Exception {
		accessToken = getAccessToken();
		String baiduApiUrl = baiduUrl + "?access_token=" + accessToken;
		String base64 = Base64Util.encode(FileUtil.readFileByBytes(imgData));
//		String param = "image="+URLEncoder.encode(base64,"UTF-8");
		String param = "image="+URLEncoder.encode(base64,"UTF-8")+"&language_type=CHN_ENG&detect_direction=true&detect_language=true&probability=true";
		String result = HttpUtil.post(baiduApiUrl, accessToken, param);
		return result;
	}
	
	/**
	 * 获取token值
	 * @return
	 */
	private static String getAccessToken() {
		try{
			if(StringUtils.isNullOrEmpty(accessToken)) {
				String jsonStr = HttpUtil.getPostHttpReponseBody(Constants.IS_PROXY,accessTokenUrl,null);
				JSONObject json = JSONObject.parseObject(jsonStr);
				if(json.containsKey("access_token")) {
					accessToken = json.getString("access_token");
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
			return getAccessToken();
		}
		return accessToken;
	}
	
	/**
	 * 根据图片数据调用百度ocr-api接口数据处理后，返回文字坐标
	 * @param imgData
	 * @return
	 * @throws Exception
	 */
	public static String getBaiduOcrLocation(String imgData, String targetTxt) throws Exception {
		StringBuffer locationResult = new StringBuffer();
		String result = BaiduApiUtils.getBaiduApiForAccurate(imgData);
		String jsonType = StringUtils.getJsonType(result);
		if(Constants.JSON_STRING.equals(jsonType)) {
			JSONObject json = JSONObject.parseObject(result);
			if(json.containsKey("words_result") && json.get("words_result")!=null){
				JSONArray array = json.getJSONArray("words_result");
				String targetWordString = "";
				for (int i = 0; i < array.size(); i++) {
					JSONObject jsonObject = array.getJSONObject(i);
					String wordString = jsonObject.getString("words");
					targetWordString = wordString.replace("请点击图中的“", "").replace("”字", "");
					if(!targetWordString.contains(targetTxt)) {
						continue;
					}
					
					if(targetWordString.contains(targetTxt) && !wordString.contains("请点击图中的")) {
						JSONObject  locationJson = JSONObject.parseObject(jsonObject.getString("location"));
						Integer top = locationJson.getInteger("top");
						Integer left = locationJson.getInteger("left");
						locationResult.append(top).append(",").append(left);
//						System.out.println("top==>" + top + "，left===>" + left);
						break;
					}
				}
			}
		}
		return locationResult.toString();
	}
}